package net.jescort.web.servlet.controller.auth;

import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class SignupValidator implements Validator
{
    private static final String SIMPLE_EMAIL_REGEX = "[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
    
    public boolean supports(Class<?> clazz)
    {
        return SignupFormBean.class.isAssignableFrom(clazz);
    }
    
    public void validate(Object object, Errors errors)
    {
        SignupFormBean formBean = (SignupFormBean)object;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.username.empty", "Please specify a username.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email.empty", "Please specify an email address.");
        if(StringUtils.isNotBlank(formBean.getEmail()) && !Pattern.matches(SIMPLE_EMAIL_REGEX, formBean.getEmail().toUpperCase()))
        {
            errors.rejectValue("email", "error.email.invalid", "Please enter a valid email address.");
        }
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "error.password.empty", "Please specify a password.");
    }
}
